package com.common.tools;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import org.apache.log4j.Logger;

import com.common.util.PropertyUtils;
import com.sun.mail.smtp.SMTPTransport;

/**
 * 邮件工具类
 * 
 * @author chenlujun
 * @version [版本号, 2014-11-20]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class MailTools {
	
	private static Logger logger = Logger.getLogger(MailTools.class);

	private static MailTools mailTools = null;

	public static MailTools getInstance() {
		if (mailTools == null) {
			mailTools = new MailTools();
		}
		return mailTools;
	}
	
	/**
	 * 发送邮件
	 * 
	 * @param receiver
	 *            邮件接收者邮箱
	 * @param title
	 *            邮件标题
	 * @param context
	 *            邮件内容
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	public void send(String receiver, String title, String context) {

		ExecutorService pool = Executors.newCachedThreadPool();
		SendMail sendMail = new SendMail(receiver, title, context);
		pool.execute(sendMail);
		
	}

	public class SendMail extends Thread {

		private String receiver;
		private String title;
		private String context;

		public SendMail(String receiver, String title, String context) {
			this.receiver = receiver;
			this.title = title;
			this.context = context;
		}

		/** 发送邮件处理 */

		@Override
		public void run() {
			String host = PropertyUtils.getValue("mail.host");
			String from = PropertyUtils.getValue("mail.account.from");
			String user = PropertyUtils
					.getValue("mail.account.from.login.name");
			String password = PropertyUtils
					.getValue("mail.account.from.login.password");
			String prot = PropertyUtils.getValue("mail.port");

			Properties props = new Properties();
			props.put("mail.smtp.host", host);
			props.put("mail.from", from);
			props.put("mail.smtp.auth", "true");
			Session session = Session.getInstance(props, null);

			try {

				Message msg = new MimeMessage(session);
				msg.setFrom();
				msg.setRecipients(Message.RecipientType.TO,
						InternetAddress.parse(receiver, false));
				msg.setSentDate(new Date());
				msg.setHeader("X-Mailer", "sendhtml");

				msg.setSubject(title);

				ByteArrayInputStream bais = new ByteArrayInputStream(
						context.getBytes());
				BufferedReader in = new BufferedReader(new InputStreamReader(
						bais));
				collect(in, msg);

				SMTPTransport t = (SMTPTransport) session.getTransport(prot);
				try {
					t.connect(host, user, password);
					t.sendMessage(msg, msg.getAllRecipients());
				} finally {
					String reslutStr = t.getLastServerResponse();
					t.close();

					logger.debug("邮件发送结果：" + reslutStr);

				}

			} catch (MessagingException ex) {
				logger.error("邮件发送失败，" + ex);
			} catch (IOException ex) {
				logger.error("邮件发送失败，" + ex);
			} catch (Exception ex) {
				logger.error("邮件发送失败，" + ex);
			}

		}

		/**
		 * 拼接邮件内容
		 * 
		 * @param in
		 *            邮件正文内容
		 * @param msg
		 *            邮件消息体
		 * @throws MessagingException
		 * @throws IOException
		 * @see [类、类#方法、类#成员]
		 */
		private void collect(BufferedReader in, Message msg)
				throws MessagingException, IOException {
			String line;
			StringBuffer sb = new StringBuffer();
			sb.append("<HTML>\n");
			sb.append("<HEAD>\n");
			sb.append("<TITLE>\n");
			sb.append("</TITLE>\n");
			sb.append("</HEAD>\n");

			sb.append("<BODY>\n");

			while ((line = in.readLine()) != null) {
				sb.append(line);
				sb.append("\n");
			}

			sb.append("</BODY>\n");
			sb.append("</HTML>\n");

			msg.setDataHandler(new DataHandler(new ByteArrayDataSource(sb
					.toString(), "text/html")));
		}

	}

}
